package cn.dglydrpy.study.smartmvc.base.listener;

import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.dglydrpy.study.smartmvc.base.common.HandlerMapping;
/**
 * 通过lisener加载配置文件
 */
public class ContextConfigListener implements ServletContextListener {
	
	public HandlerMapping loadControlers(String xml) throws Exception {
		SAXReader reader = new SAXReader();
		InputStream in = ContextConfigListener.class.getClassLoader().getResourceAsStream(xml);
		Document doc = reader.read(in);
		in.close();
		Element root = doc.getRootElement();//beans
		List<Element> list=root.elements("bean"); 
		HandlerMapping mapping = new HandlerMapping();
		for(Element e:list) {
			String className=e.attributeValue("class");
			mapping.init(className);
		}
		return mapping;
	}
	
    public void contextInitialized(ServletContextEvent e)  {
    	try {
	    	ServletContext ctx = e.getServletContext();
	    	HandlerMapping mapping = loadControlers("smartMVC.xml");
	    	String path = ctx.getContextPath();
	    	ctx.setAttribute("root", path); 
	    	ctx.setAttribute("handlerMapping", mapping);
    	}catch(Exception ex) {
    		ex.printStackTrace();
    		throw new RuntimeException(ex);
    	}
    }
    
    public void contextDestroyed(ServletContextEvent arg0)  {}
}
